using System.Collections.Generic;
using System.IO;
using Cysharp.Threading.Tasks;
using Data.Bag;
using Entity.Player;
using Map.MapObject.Building;
using MoonFramework.Scripts.Tool;
using MoonFramework.Template;
using Tool;
using UnityEngine;
using UnityEngine.UI;

namespace UI.Bag
{
    /// <summary>
    /// 储物箱UI
    /// </summary>
    [UIElement(true,"UI/UI_StorageBoxWindow", 1)]
    public class UI_StorageBoxWindow : UI_BagWindow
    {
        [SerializeField] private Button _closeButton;
        [SerializeField] private Transform itemParent;
        private StorageBox _storageBox;
            
        public override void Init()
        {
            base.Init();
            _slots = new List<UI_ItemSlot>(10);
            _closeButton.onClick.AddListener(CloseButtonClick);
        }

        public void Init(StorageBox storageBox, BagData bagData, Vector2Int size)
        {
            _storageBox = storageBox;
            InitData(bagData, size).Forget();
        }

        public async UniTaskVoid InitData(BagData bagData,Vector2Int size)
        {
            _bagData = bagData;
            SetWindowSize(size);
            //生成格子
            int count = bagData.ItemDataList.Length;
            string pathName = Path.Combine("UI", nameof(UI_ItemSlot));
            for (int i = 0; i < count; i++)
            {   
                GameObject slotObj = await GameObjPoolManager.Instance.PopAsync<GameObject>(pathName);
                var slot = slotObj.GetComponent<UI_ItemSlot>();
                slotObj.transform.SetParent(itemParent);
                slot.Init(i, this);
                slot.InitData(bagData.ItemDataList[i]);
                _slots.Add(slot);
            }
        }

        private void SetWindowSize(Vector2Int size)
        {
            //宽度 = 两边15 + 中间格子区域
            //高度 = 上方50 + 中间格子区域 + 底部15
            RectTransform rectTransform = (RectTransform)transform;
            rectTransform.sizeDelta = new Vector2(30 + size.x * 100, 65 + size.y * 100);
        }
        
        private void Update()
        {
            if (PlayerController.Instance != null)
            {
                if (Vector2.Distance(PlayerController.Instance.Player.viewController.transform.position,
                        _storageBox.transform.position) >= 1)
                {
                    CloseButtonClick();
                }
            }
        }
        
        private void CloseButtonClick()
        {
            ProjectTool.PlayAudio(PlayerAudioName.Bag);
            Close();
        }
        
        public override void Close()
        {
            base.Close();
            for(int i = 0; i < _slots.Count; i++)
            {
                _slots[i].gameObject.MoonGameObjPushPool();
            }
            _slots.Clear();
            _bagData = null;
        }
    }
}